package com.unina.dropplayer.common;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;

import android.content.Context;
import android.os.AsyncTask;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;

import com.dropbox.client2.DropboxAPI;
import com.dropbox.client2.DropboxAPI.Entry;
import com.unina.dropplayer.play.SongInfo;
import com.unina.dropplayer.utilities.RootFolderBuilder;

public class GetFileListTask extends AsyncTask<Void, Long, ArrayList<SongInfo>> {

	private Context mContext;
	private DropboxAPI<?> mApi;
	private String mPath;
	private ListView listView;
	private ListAdapter adapter;
	private ArrayList<SongInfo> songsList = new ArrayList<SongInfo>();

	public GetFileListTask(Context mContext, DropboxAPI<?> mApi, String mPath,
			ListView listView, ListAdapter adapter) {
		super();
		this.mContext = mContext;
		this.mApi = mApi;
		this.mPath = mPath;
		this.listView = listView;
	}

	@Override
	protected ArrayList<SongInfo> doInBackground(Void... arg0) {
		Entry rootFolderMetadata;
		Collection<Entry> audioFiles;
		List<String> fileNameList = null;
		
		rootFolderMetadata = RootFolderBuilder.createRootFolder(mApi);
		

		
        if (null==rootFolderMetadata || !rootFolderMetadata.isDir || rootFolderMetadata.contents == null) {
            return null;
        }
		
        fileNameList =  new ArrayList<String>();
		audioFiles =rootFolderMetadata.contents;
		
		for (Entry entry : audioFiles) {
			fileNameList.add(entry.fileName());
			HashMap<String, String> song = new HashMap<String, String>();
			song.put("songTitle", entry.fileName().substring(0, (entry.fileName().length() - 4)));
			song.put("songPath", entry.fileName());
			
			// Adding each song to SongList
			songsList.add(new SongInfo(entry.fileName(), entry.fileName().substring(0, (entry.fileName().length() - 4))));
		}
		
		
		adapter = new ArrayAdapter<String>(mContext, 
		        android.R.layout.simple_list_item_1, fileNameList.toArray(new String[fileNameList.size()]));

		return songsList;
	}
	

	
    @Override
    protected void onPostExecute(ArrayList<SongInfo> result) {
    	if(null!=listView){
    		listView.setAdapter(adapter);
    	}
    }

}
